#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
测试运行脚本
用于运行pytest测试并生成Allure报告
"""

import os
import sys
import subprocess
import time
from datetime import datetime

def run_tests():
    """运行测试并生成Allure报告"""
    print("=" * 60)
    print("开始运行测试...")
    print("=" * 60)
    
    # 确保reports目录存在
    os.makedirs("reports", exist_ok=True)
    os.makedirs("reports/allure-results", exist_ok=True)
    os.makedirs("reports/allure-report", exist_ok=True)
    
    # 运行pytest测试
    cmd = [
        sys.executable, "-m", "pytest",
        "--alluredir=./reports/allure-results",
        "--clean-alluredir",
        "-v"
    ]
    
    print(f"执行命令: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    # 输出测试结果
    print("\n" + "=" * 60)
    print("测试执行结果:")
    print("=" * 60)
    print(result.stdout)
    if result.stderr:
        print("错误信息:")
        print(result.stderr)
    
    return result.returncode

def generate_allure_report():
    """生成Allure HTML报告"""
    print("\n" + "=" * 60)
    print("生成Allure报告...")
    print("=" * 60)
    
    # 检查allure命令是否可用
    try:
        subprocess.run(["allure", "--version"], capture_output=True, check=True)
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("警告: Allure命令行工具未安装或不在PATH中")
        print("请安装Allure: https://docs.qameta.io/allure/#_installing_a_commandline")
        return False
    
    # 生成HTML报告
    cmd = [
        "allure", "generate",
        "./reports/allure-results",
        "-o", "./reports/allure-report",
        "--clean"
    ]
    
    print(f"执行命令: {' '.join(cmd)}")
    result = subprocess.run(cmd, capture_output=True, text=True)
    
    if result.returncode == 0:
        print("Allure报告生成成功!")
        print(f"报告位置: {os.path.abspath('./reports/allure-report/index.html')}")
        return True
    else:
        print("Allure报告生成失败:")
        print(result.stderr)
        return False

def open_allure_report():
    """打开Allure报告"""
    report_path = os.path.abspath("./reports/allure-report/index.html")
    if os.path.exists(report_path):
        print(f"\n正在打开报告: {report_path}")
        try:
            import webbrowser
            webbrowser.open(f"file://{report_path}")
        except Exception as e:
            print(f"无法自动打开报告: {e}")
            print(f"请手动打开: {report_path}")
    else:
        print("报告文件不存在")

def main():
    """主函数"""
    start_time = time.time()
    
    # 运行测试
    test_result = run_tests()
    
    # 生成报告
    if test_result == 0 or test_result == 1:  # pytest成功或部分失败都生成报告
        report_success = generate_allure_report()
        if report_success:
            open_allure_report()
    
    end_time = time.time()
    duration = end_time - start_time
    
    print("\n" + "=" * 60)
    print(f"测试执行完成，耗时: {duration:.2f}秒")
    print("=" * 60)
    
    return test_result

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code) 